package com.cictec.middleware.gps.engine.thread;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.atomic.AtomicInteger;

import com.cictec.middleware.core.pojo.MiddlewarePosition;
import com.cictec.middleware.gps.engine.TimeEventBus;
import com.cictec.middleware.gps.engine.TimingObject;

public class PointExecutor {

	private ThreadPoolExecutor executor = null;

	private List<String> devcodeList = new ArrayList<String>();
	private TimeEventBus timeEventBus;
	private int maxSize = 10;
	private String threadPoolName;

	/**
	 * 
	 * @param timeEventBus
	 * @param maxSize  支持最大maxSize个设备执行
	 */
	public PointExecutor(TimeEventBus timeEventBus, int maxSize, ThreadPoolExecutor executor, String threadPoolName) {
		this.timeEventBus = timeEventBus;
		this.maxSize = maxSize;
		this.executor = executor;
		this.threadPoolName = threadPoolName;
//		executor = Executors.newFixedThreadPool(1, getThreadFactory());

	}

	/**
	 * 执行
	 * 
	 * @param event
	 * @param timeEventBus
	 */
	public void execute(MiddlewarePosition position) {
//		executor.submit(new PointRunable(timingObject, timeEventBus));
		executor.execute(new PositionExecutorRunable(position, timeEventBus));
	}
	/**
	 * 执行
	 * 
	 * @param event
	 * @param timeEventBus
	 */
	public void execute(TimingObject timingObject) {
//		executor.submit(new PointRunable(timingObject, timeEventBus));
		executor.execute(new PointExecutorRunable(timingObject, timeEventBus));
	}
	
	public void shutdown(){
		executor.shutdown();
	}

	/**
	 * 添加设备到该线程中
	 * 
	 * @param devcode
	 */
	public void addDevcode(String devcode) {
		devcodeList.add(devcode);
	}

	/**
	 * 该线程中是否已经达到最大执行数据的devcode
	 * 
	 * @return
	 */
	public boolean isMaxDispatcher() {
		return devcodeList.size() == maxSize;
	}

	/**
	 * 任务线程是否包含该devcode
	 * 
	 * @param devcode
	 * @return
	 */
	public boolean contains(String devcode) {
		return devcodeList.contains(devcode);
	}

	public String getThreadPoolName(){
		return threadPoolName;
	}
	
	/**
	 * 移除监控任务devcode
	 * 
	 * @param devocde
	 */
	public void remove(String devocde) {
		devcodeList.remove(devocde);
	}
	
	public List getDevice(){
		return devcodeList;
	}
	
	public ThreadPoolExecutor getExecutor(){
		return this.executor;
	}
	
	/**
	 * 获取线程池工厂
	 * 
	 * @return
	 */
	private ThreadFactory getThreadFactory() {
		return new ThreadFactory() {
			AtomicInteger sn = new AtomicInteger();

			public Thread newThread(Runnable r) {
				SecurityManager s = System.getSecurityManager();
				ThreadGroup group = (s != null) ? s.getThreadGroup() : Thread.currentThread().getThreadGroup();
				Thread t = new Thread(group, r);
				t.setName("point-execute-thread-" + sn.incrementAndGet());
				return t;
			}
		};
	}

}
